import React, { RefObject } from "react";
import { Form, Input, Button, Checkbox } from "antd-mobile";
import request from "../../api/request";
import { rsaEncrypt } from "../../hooks/useJsencrypt";
import Navbar from "../../compounts/navber/Navbar";
import { UserOutline, LockFill } from "antd-mobile-icons";
import style from './login.module.css'
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { logininfor } from '../../store/stateSlice/user'

// 1. 添加表单引用
function Index() {
    const nav = useNavigate();
    const dispatch = useDispatch();
    const [form] = Form.useForm(); // 添加这一行

    // 2. 设置表单初始值
    React.useEffect(() => {
        form.setFieldsValue({ agreement: false });
    }, [form]);

    // 3. 修改提交处理函数
    const onFinish = async (values) => {
        console.log(values);
        try {
            // 显式验证表单
            await form.validateFields();

            // 创建一个URLSearchParams对象
            const params = new URLSearchParams({
                email:values.email,//获取邮箱
                pwd:rsaEncrypt(values.pwd) //获取密码并通过封装的方法加密
            })
            const response = await request.post("/user/v1/login", params);
            console.log(response);
            if (response.data.status === "0000") {
                // 跳转页面
                nav('/home')
                // 存储登录信息到redux
                dispatch(logininfor(response.data.result))
                // 存储头像到本地
                localStorage.setItem('username', response.data.result.nickName);
                localStorage.setItem("touxiang", response.data.result.headPic);
                localStorage.setItem("sessionId", response.data.result.sessionId);
                localStorage.setItem("userId", response.data.result.userId);
                // alert("登录成功");
            } else {
                // alert(`登录失败: ${response.data.message}`);
            }
        } catch (e) {
            // 处理验证失败或其他错误
            console.error("登录失败:", e.response ? e.response.data : e.message);
            if (e.errorFields && e.errorFields.length > 0) {
                // 显示验证错误信息
                alert(e.errorFields[0].errors[0]);
            } else {
                alert("登录失败，请稍后重试");
            }
        }
    };

    // 4. 修改 Form 组件配置
    return (
        <div className={style.box}>
            <Navbar title={'登录'}></Navbar>
            <div className={style.title}>人民健康通行证</div>
            <Form
                form={form}
                initialValues={{ agreement: false }}
                layout="horizontal"
                onFinish={onFinish}
                requiredMarkStyle='none'
                style={{ '--border-bottom': 'none', '--border-top': 'none' }}
                footer={
                    <Button block type="submit" shape='rounded' color="primary" size="large">
                        提交
                    </Button>
                }
            >
                {/* 账号 */}
                <Form.Item
                    name="email"
                    label={<UserOutline style={{ color: '#f55a55' }} />}
                    rules={[{ required: true, message: "姓名不能为空" }]}
                    style={{ '--prefix-width': '40px', textAlign: 'center', fontSize: '20px' }}
                >
                    <Input placeholder="请输入邮箱号" />
                </Form.Item>
                {/* 密码 */}
                <Form.Item
                    name="pwd"
                    label={<LockFill style={{ color: '#f55a55' }} />}
                    rules={[{ required: true, message: "密码不能为空" }]}
                    style={{ '--prefix-width': '40px', textAlign: 'center', fontSize: '20px' }}
                >
                    <Input placeholder="请输入密码" />
                </Form.Item>

                <Form.Item
                    name="agreement"
                    valuePropName="checked"
                    style={{ textAlign: 'center' }}
                    rules={[{
                        validator: (_, value) =>
                            value ? Promise.resolve() : Promise.reject(new Error('请同意服务协议和隐私政策'))
                    }]}
                >
                    <Checkbox style={{ marginTop: '50px', '--font-size': '15px' }}>登录即同意 <span className={style.xieyi}>《服务协议》</span>和
                        <span className={style.xieyi}>《隐私政策》</span></Checkbox>
                </Form.Item>
            </Form>
            <div className={style.loginBtn} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: '10px' }}>
                <span>密码登录</span>
                <span>|</span>
                <span
                    style={{ color: '#1890ff', textDecoration: 'underline', cursor: 'pointer' }}
                    onClick={() => nav('/register')}
                >
                    还没有账号去注册
                </span>
            </div>
        </div>
    );
}

export default Index;
